package com.leap.meeting.util;

import java.sql.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class DataUtil {

    public static ResultSet querySet(String sql, Object... obj) throws SQLException {
        //1.获取连接
        Connection connection = JDBCUtil.getConnection();

        //2.预编译SQL语句
        PreparedStatement preparedStatement = connection.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

        //3.为占位符取值,执行SQL,接受返回结果
        if(obj != null && obj.length > 0){
            for (int i = 0; i < obj.length; i++) {
                preparedStatement.setObject(i+1, obj[i]);
            }
        }

        //4.执行SQL 并接受返回的结果集
        ResultSet resultSet = preparedStatement.executeQuery();

        return resultSet;
    }

    public static Object[][] getArrays(ResultSet set) throws SQLException {
        Object[][] objects;
        set.last();
        int rowcount = set.getRow();
        ResultSetMetaData rsm = set.getMetaData();
        int colcount = rsm.getColumnCount();//获取列数
        System.out.println(rowcount + " " + colcount);
//      创建二维数组
        objects = new Object[rowcount][colcount];
        set.first();
        for (int i = 0; i < rowcount; i++) {
            for (int j = 0; j < colcount; j++) {
                objects[i][j] = set.getObject(j + 1);
            }
            set.next();
        }

        return objects;
    }

    public static Date asDate(LocalDateTime localDateTime){
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }
}
